﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using finProj.Entities;

namespace finProj.Gui
{
    public partial class Form3 : Form
    {
        string[] filenames;
        private List<clusterBoxes> clustersView;
        private bool stopped = false;

        public Form3()
        {
            InitializeComponent();
            if (Settings.Instance.state == 1)
            {
                openImageToolStripMenuItem.Enabled = false;
                loadDatasetToolStripMenuItem.Enabled = true;
                clustersToolStripMenuItem.Enabled = false;
            }
        }

        private void openImageToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void loadDatasetToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }


        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Dispose();
            Application.Exit();
        }

        private void viewToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void helpToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void openHelpDocumentToolStripMenuItem_Click(object sender, EventArgs e)
        {
           Help.Instance.Show();
        }

        private void PathWord_TextChanged(object sender, EventArgs e)
        {

        }

        private void PathBox_TextChanged(object sender, EventArgs e)
        {

        }
        void Form3_Closed(object sender, EventArgs e)
        {
            this.Dispose();
            Application.Exit();
        }

        private void BrowseButton_Click(object sender, EventArgs e)
        {
            
            string path;
            var openFiledlg = new OpenFileDialog();
            openFiledlg.Filter = "Images (*.jpg, *.png, *.bmp) |*.jpg;*.png;*.bmp";
            openFiledlg.Multiselect = true;
            DialogResult res = openFiledlg.ShowDialog();

            if (res == DialogResult.OK)
            {
                filenames = openFiledlg.FileNames;
                path = Path.GetDirectoryName(filenames[0]);
                Settings.Instance.path = path;
                PathBox.Text = path;


            }
        }

        private void PleaseEnterNumberWord_TextChanged(object sender, EventArgs e)
        {

        }

        private void EnterNumberBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                e.Handled = true;
            }

        }

        private void GoButton_Click(object sender, EventArgs e)
        {
            stopped = false;
            if (PathBox.Text.Length > 0 && EnterNumberBox.Text.Length > 0 )
            {
                int persons = int.Parse(EnterNumberBox.Text);
                if (persons > 0 && persons <= int.Parse(EnterNumberBox.Text))
                {
                    this.progressBar1.Minimum = 0;
                    this.progressBar1.Maximum = filenames.Length;
                    this.progressBar1.Visible = true;
                    this.Refresh();
                    

                    var mngr = new PictureManager();

                    foreach (var filename in filenames)
                    {
                        if (!stopped)
                        {
                            var pic = new Picture(filename);
                            pic.detectFace();
                            if (pic.detectFeatures())
                            {
                                mngr.AddPicture(pic);
                            }
                            
                        
                            this.progressBar1.Value++;
                        }
                        
                    }
                    this.progressBar1.Visible = false;
                    this.progressBar1.Value = 0;

                    Settings.Instance.picManager = mngr;
                    Settings.Instance.numberOfPeople = persons;

                    mngr.AddExistingKeys();
                    var kmeans = new KMeans();

                    kmeans.DoKmeansAlgorithm();
                    //var mini = new minimizationMatrix();
                    //Settings.Instance.SetMinimizationMatrix(mini.DoMinimizationMatrix());


                    this.GoButton.Visible = false;
                    this.BrowseButton1.Enabled = false;
                    DrawPanel1();



                    Settings.Instance.state = 2;
                    openImageToolStripMenuItem.Enabled = true;
                    loadDatasetToolStripMenuItem.Enabled = false;
                    clustersToolStripMenuItem.Enabled = true;
                }
            }
            else
            {
                //show error
            }
            
            
        }

        public void DrawPanel1()
        {
            this.panel1.Dispose();
            this.panel1 = new Panel();

            this.panel1.BackColor = System.Drawing.SystemColors.InactiveBorder;
            this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.panel1.Location = new System.Drawing.Point(4, 116);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(536, 244);
            this.panel1.TabIndex = 8;
            this.panel1.Visible = false;


            this.clustersView = new List<clusterBoxes>();
            int persons = Settings.Instance.numberOfPeople;

            for (int i = 0; i < persons; i++)
            {
                this.clustersView.Add(new clusterBoxes());
                var SaveButton = new System.Windows.Forms.Button();
                SaveButton.Location = new System.Drawing.Point(114, 56 + 85 * i);
                SaveButton.Name = "SaveButton" + i;
                SaveButton.Size = new System.Drawing.Size(79, 20);
                SaveButton.TabIndex = 3;
                SaveButton.Text = "Save";
                SaveButton.UseVisualStyleBackColor = true;
                SaveButton.Click += new System.EventHandler(SaveButton_Click);

                var textBox1 = new System.Windows.Forms.TextBox();
                textBox1.ForeColor = System.Drawing.SystemColors.WindowFrame;
                textBox1.Location = new System.Drawing.Point(114, 20 + 85 * i);
                textBox1.Name = "textBox" + i;
                textBox1.Size = new System.Drawing.Size(321, 20);
                textBox1.TabIndex = 2;
                textBox1.Text = "Please enter the name of the person";
                textBox1.Click += textBox1_Click;

                var pictureBox1 = new System.Windows.Forms.PictureBox();
                pictureBox1.BackColor = System.Drawing.SystemColors.ControlLightLight;
                pictureBox1.Location = new System.Drawing.Point(9, 8 + 85 * i);
                pictureBox1.Name = "pictureBox" + i;
                pictureBox1.Size = new System.Drawing.Size(79, 79);
                pictureBox1.TabIndex = 1;
                pictureBox1.TabStop = false;
                pictureBox1.MouseHover += new EventHandler(pictureBox1_MouseHover);
                pictureBox1.MouseLeave += new EventHandler(pictureBox1_MouseLeave);
                if (Settings.Instance.clusterManager.clusters.Count != 0)
                {
                    if (Settings.Instance.clusterManager.clusters[i].pictures != null &&
                        Settings.Instance.clusterManager.clusters[i].pictures.Count != 0)
                    {
                        pictureBox1.Image =
                            Settings.Instance.clusterManager.clusters[i].pictures[0].origPicture.Resize(80,
                                                                                                        80,
                                                                                                        INTER
                                                                                                            .
                                                                                                            CV_INTER_LINEAR)
                                .ToBitmap();
                    }
                    else
                    {
                        pictureBox1.Image = new Image<Bgr, Byte>("NoPictures.png").ToBitmap();
                        pictureBox1.Name = "NoPictures";
                    }
                }
                else
                {
                    pictureBox1.Image = new Image<Bgr, Byte>("NoPictures.png").ToBitmap();
                    pictureBox1.Name = "NoPictures";
                }

                ToolTip tt = new ToolTip();
                tt.SetToolTip(pictureBox1, "In order to view the picutres, please click on this picture");
                pictureBox1.Click += pictureBox1_Click;


                clustersView[i].textBox1 = textBox1;
                clustersView[i].SaveButton = SaveButton;
                clustersView[i].pictureBox1 = pictureBox1;

                this.panel1.Controls.Add(SaveButton);
                this.panel1.Controls.Add(textBox1);
                this.panel1.Controls.Add(pictureBox1);

            }
            this.editbtn.Visible = true;
            this.loadImgbutton.Visible = true;
            this.Controls.Add(this.panel1);
            this.panel1.AutoScroll = true;
            this.panel1.Visible = true;
            this.GotFocus += new EventHandler(Form3_GotFocus);
            this.Refresh();
        }

        void pictureBox1_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        void pictureBox1_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        void Form3_GotFocus(object sender, EventArgs e)
        {
            DrawPanel1();
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            PictureBox pic = (PictureBox)sender;
            if(pic.Name != "NoPictures" )
            {
                int diff = pic.Name.Length - "pictureBox".Length;

                string ch = "";
                for (int i = diff; i > 0; i--)
                {
                    ch += pic.Name[pic.Name.Length - i];
                }

                //char ch = pic.Name[pic.Name.Length - 1];
                int j = int.Parse(ch);

                var clusterPrev = new clusterPreview(j);
                clusterPrev.Show();
            }
            
        }

        private void textBox1_Click(object sender, EventArgs e)
        {
            TextBox t = (TextBox) sender;
            string textboxname = t.Name;

            for (int i = 0; i < this.clustersView.Count; i++)
            {
                if (clustersView[i].textBox1.Name == textboxname)
                {
                    clustersView[i].textBox1.Text = "";
                    break;
                }
            }


        }

        private void SaveButton_Click(object sender, EventArgs e)
        {
            Button b = (Button) sender;
            string ch = "";
            int diff = b.Name.Length - "SaveButton".Length;

            for (int i = diff; i > 0; i--)
            {
                ch += b.Name[b.Name.Length - i];
            }

            //char id = buttonname[buttonname.Length - 1];


            for (int i = 0; i < this.clustersView.Count; i++)
            {
                if (clustersView[i].textBox1.Name == "textBox" + ch 
                    && clustersView[i].textBox1.Text != "Please enter the name of the person" 
                    && clustersView[i].textBox1.Text != "")
                {
                    Settings.Instance.setName(i, clustersView[i].textBox1.Text);
                    clustersView[i].textBox1.Enabled = false;
                    break;
                }
                
            }
            b.Enabled = false;


        }

        private void FinishButton_Click(object sender, EventArgs e)
        {
            this.Dispose();
            Application.Exit();
        }

        private void editbtn_Click(object sender, EventArgs e)
        {
            var clusteredit = new clustersEdit(this);
            clusteredit.Show();


        }

        private void loadImgbutton_Click(object sender, EventArgs e)
        {
            var form2 = new Form2();
            form2.Show();
            this.Dispose();
        }

        private void clustersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var clsedit = new clustersEdit(this);
            clsedit.Show();
        }

        
    }


    class clusterBoxes
    {
        public System.Windows.Forms.Button SaveButton;
        public System.Windows.Forms.TextBox textBox1;
        public System.Windows.Forms.PictureBox pictureBox1;
    }


}
